/**
 * @Title: model.js
 * @Description: model
 * @author: Fanchao
 * @date: 2020/10/3 3:01 下午
 * @version V1.0
 */

import { pathToRegexp } from 'path-to-regexp';
import { message } from 'antd';
import {
    reqDetailEntry,
    reqUpdateEntry
} from 'api/index';

export default {
    namespace: 'entryEditDetail',
    state: {
        entryDetail: {},
        iconList: [],
    },
    reducers: {
        setEntryEditDetail(state, { payload: entryDetail }) {
            return { ...state, entryDetail };
        },
        setIconList(state, { payload: iconList }) {
            return { ...state, iconList };
        },
    },
    effects: {
        * getEntryEditDetail({ payload }, { call, put, select }) {
            const result = yield call(reqDetailEntry, payload);
            if (result.status === 1) {
                const entryDetail = result.data;
                yield put({
                    type: 'setEntryEditDetail',
                    payload: entryDetail,
                });
                const iconList = result.data.icon.split(',').map((item, index) => {
                    return {
                        uid: index,
                        name: item,
                        status: 'done',
                        url: item,
                    };
                });
                yield put({
                    type: 'setIconList',
                    payload: iconList,
                });
            } else {
                message.error(result.message);
            }
        },
        * updateEntry({ payload, callback }, { call, put, select }) {
            const result = yield call(reqUpdateEntry, payload);
            if (result.status === 1) {
                if (callback && typeof callback === 'function') {
                    callback(result);
                }
            } else {
                message.error(result.message);
            }
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                if (pathToRegexp('/category-manage/e-category/edit').exec(pathname)) {
                    dispatch({
                        type: 'getEntryEditDetail',
                        payload: {
                            id: query.id,
                        },
                    });
                }
            });
        },
    },
};
